package webservice.functions;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.ProduceMime;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import org.apache.log4j.Logger;

import webservice.dbConnection.ConnectionHelper;
import webservice.helper.HelperClass;

@Path("/updateIP")
public class UpdateIPResource {
	
	/**
	 * a logger to log errors, debug information, etc.
	 */
	private static Logger LOG = Logger.getLogger(UpdateIPResource.class);
	
	@GET
	@ProduceMime("text/html")
	public String updateIP(@QueryParam("apiKey") @DefaultValue("") String apiKey,
						   @QueryParam("playerId") @DefaultValue("") String playerId,
						   @Context HttpServletRequest request)
	{
		//is apiKey correct?
		if(!apiKey.equals(HelperClass.getProperty("apiKey"))) {
			throw new WebApplicationException(Response.Status.FORBIDDEN);
		}
		//is there a playerId given?
		if(playerId.equals("")) {
			throw new WebApplicationException(Response.Status.BAD_REQUEST); 
		}
		LOG.debug("updating ip of player: '" + playerId + "' to IP: " + request.getRemoteAddr());
		
		Connection connection = null;
		Statement statement = null;
		try {
			
			connection = ConnectionHelper.getConnection();
			statement = connection.createStatement();
			
			String sql = "UPDATE player SET ip_address = '" + request.getRemoteAddr() + "' WHERE player_id = '" + playerId +"'";
			statement.execute(sql);
		} catch (SQLException e) {
			LOG.error(e);
		}
		
		return request.getRemoteAddr();
	}

}
